<?php

namespace app\modules\Admin\models;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use memberModel;

class memberpickgoodscardModel extends Model
{
    use SoftDeletes;

    protected $table = 'member_pickgoods_card';
    protected $primaryKey = 'id';
    protected $appends = ['expire_text'];

    protected $hidden = [];

    /**
     * @param DateTimeInterface $date
     * @return string
     */
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * @return string
     */
    public function getExpireTextAttribute()
    {
        $expire = $this->attributes['expire'];
        if($expire === null){
            $expire_text = '长期有效';
        }else{
            $expire_int = strtotime($expire);
            $now_int = time();
            if($expire_int < $now_int){
                $expire_text = '已过期';
            }else{
                if (($expire_int - $now_int) < 3600 * 24 * 1){
                    $expire_text = '1天内过期';
                }elseif (($expire_int - $now_int) > 3600 * 24 * 1 && ($expire_int - $now_int) < 3600 * 24 * 7){
                    $expire_text = '7天内过期';
                }elseif (($expire_int - $now_int) > 3600 * 24 * 7 && ($expire_int - $now_int) < 3600 * 24 * 30){
                    $expire_text = '30天内过期';
                }elseif (($expire_int - $now_int) > 3600 * 24 * 30 && ($expire_int - $now_int) < 3600 * 24 * 60){
                    $expire_text = '60天内过期';
                }elseif (($expire_int - $now_int) > 3600 * 24 * 60 && ($expire_int - $now_int) < 3600 * 24 * 90){
                    $expire_text = '90天内过期';
                }else{
                    $expire_text = '剩余约'.floor(($expire_int - $now_int)/(3600*24)).'天';
                }
            }
        }
        return $expire_text;
    }

    // 生成提货卡编号
    public static function generateSn($user_id = 0)
    {
        $rand = $user_id < 9999 ? mt_rand(100000, 99999999) : mt_rand(100, 99999);
        $card_sn = date('Yzhis') . $rand;

        $id = str_pad($user_id, (24 - strlen($card_sn)), '0', STR_PAD_BOTH);

        return 'THK'.$card_sn . $id;
    }

    public function member()
    {
        return $this->hasOne(memberModel::class, 'id', 'member_id')->select(['id', 'nickname', 'realname', 'phone', 'avatar']);
    }

    public function pickgoods_card()
    {
        return $this->belongsTo(pickgoodscardModel::class, 'card_id', 'id');
    }
}